package xyz.hubery.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.bouncycastle.util.IPAddress;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springside.modules.utils.net.IPUtil;
import sun.net.util.IPAddressUtil;
import xyz.hubery.geetest.GeetestLib;
import xyz.hubery.geetest.entity.GeetestLibResult;
import xyz.hubery.geetest.enums.DigestmodEnum;
import xyz.hubery.model.R;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "极域验证的数据接口")
@RequestMapping("/gt")
public class GeetestController {

    @Autowired
    private GeetestLib geetestLib;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/register")
    @ApiOperation(value = "极验获取第一次数据包----注册")
    @ApiImplicitParam(name = "uuid", value = "用户的标识")
    public R<String> register(String uuid) throws JSONException {
        DigestmodEnum md5 = DigestmodEnum.MD5;
        // 构造极验数据包
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("digestmod", md5.getName());
        paramMap.put("user_id", uuid);
        paramMap.put("client_type", "web");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();
        paramMap.put("ip_address", ip);
        GeetestLibResult result = geetestLib.register(md5, paramMap);
        // 将结果状态写到 session 中，此处 register 接口存入 session，后续 validate 接口会取出使用
        // 注意，此 demo 应用的 session 是单机模式，格外注意分布式环境下 session 的应用
        // request.getSession().setAttribute(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY,result.getStatus());
        redisTemplate.opsForValue().set(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY + ":" + uuid, result.getStatus());
        // request.getSession().setAttribute("userId", userId);
        redisTemplate.opsForValue().set(GeetestLib.GEETEST_SERVER_USER_KEY + ":" + uuid, uuid);
        // 注意，不要更改返回的结构和值类型
        return R.ok(result.getData());
    }
}
